<template>
  <!-- 已经登陆的情况 -->
  <div v-if="islogin" v-loading="loading"></div>
  <el-dropdown @command="handlerCommand">
    <div class="menu">
      <el-avatar :size="80" :src="user.logo" alt="" />
      <el-icon class="el-icon--right">
        <arrow-down />
      </el-icon>
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          ><el-icon><User /></el-icon
          >{{ user.tbUser.username }}</el-dropdown-item
        >

        <el-dropdown-item divided command="home"
          ><el-icon><House /></el-icon>网站首页</el-dropdown-item
        >

        <el-dropdown-item divided command="userlogo"
          ><el-icon><House /></el-icon>修改头像</el-dropdown-item
        >

        <el-dropdown-item command="userpwd"
          ><el-icon><House /></el-icon>修改密码</el-dropdown-item
        >

        <el-dropdown-item command="userinfo"
          ><el-icon><House /></el-icon>修改附加信息</el-dropdown-item
        >
        <el-dropdown-item divided command="logout"
          ><el-icon><Close /></el-icon>退出登录</el-dropdown-item
        >
      </el-dropdown-menu>
    </template>
  </el-dropdown>

  <!-- 没有登陆的情况 -->
  <div v-if="!islogin">
    <el-button-group>
      <el-button @click="toPage('/user/login')" type="primary">登录</el-button>
      <el-button @click="toPage('/user/reg')" type="success">注册</el-button>
    </el-button-group>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { api } from '../../js/ajax'
import { tools } from '../../js/tools'
import { ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const handlerCommand = command => {
  if (command == 'logout') {
    api.delete('/auth', {}, () => {
      queryUser()
    })
  } else if (command == 'home') {
    router.push('/')
  } else if (command == 'userlogo') {
    modifyUserLogo()
  }
}

const modifyUserLogo = () => {
  tools.openimage(file => {
    loading.value = false
    api.uploadUserLogo(file, data => {
      if (data.success) {
        queryUser()
        return
      }
      ElMessageBox.alert(data.msg, '修改头像失败')
    })
  })
}

const toPage = page => {
  router.push(page)
}
const islogin = ref(false)
const user = ref({
  tbUser: {},
  tbUserInfo: {},
  tbRole: {},
  exInfo: {},
  logo: '',
})

const queryUser = () => {
  api.get('/auth', {}, data => {
    islogin.value = data.success
    if (data.success) {
      user.value = data.data
      user.value.logo = api.userlogo(data.data.tbUser.uid)
    } else {
      user.value = {
        tbUser: {},
        tbUserInfo: {},
        tbRole: {},
        exInfo: {},
        logo: '',
      }
    }
  })
}

queryUser()
</script>

<style scoped>
.menu {
  display: flex;
  align-items: center;
}

.menu img {
  width: 2rem;
  height: auto;
  display: block;
}
</style>
